"""
App
"""

# flake8: noqa

import traceback
from fastapi import (
    FastAPI,
    Request,
)
from loguru import logger
from starlette.responses import JSONResponse

import utils.enum_utils as enum
from components.exceptions import BusinessException
from urls import root_url

# 创建 App
app: FastAPI = FastAPI(
    title="Fast",
    description="Fast API Doc",
    debug=True,
    root_path="/"
)

# 注册根路由
app.include_router(root_url)


# 业务异常
@app.exception_handler(BusinessException)
async def business_exception_handler(
    request: Request,
    exc: BusinessException,
) -> JSONResponse:
    """
    自定义业务异常处理
    """

    return JSONResponse(
        status_code=enum.HTTPStatusCode.HTTP_200_OK.value,
        content={
            "code": exc.status_code,
            "message": exc.detail,
        },
    )


# 全局异常中间件
@app.middleware("http")
async def exception_middleware(
    request: Request,
    call_next,
):
    """
    全局异常中间件
    """

    status_200 = enum.HTTPStatusCode.HTTP_200_OK
    status_500 = enum.HTTPStatusCode.HTTP_500_INTERNAL_SERVER_ERROR

    try:
        response = await call_next(request)

    except Exception as e:  # noqa
        logger.error(f"系统内部错误: {traceback.format_exc()}")
        response = JSONResponse(
            status_code=status_200.value,
            content={
                "code": status_500.value,
                "message": status_500.label.split(" | ")[-1],
            },
        )

    return response
